package com.qfedu.labsystem.controller;

import com.alibaba.excel.EasyExcel;
import com.qfedu.labsystem.dao.UserMapper;
import com.qfedu.labsystem.entity.bo.UserBO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.ByteArrayOutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * @ClassName ExcelExportController
 * @Author ykx
 * @Date 2024/4/10 16:34
 * @Version 1.0
 */
@RestController
@RequestMapping("/adminapi")
public class ExcelExportController {

    @Autowired
    private UserMapper userMapper;

    /**
     * 导出至excel
     *
     * @return
     * @throws Exception
     */
    @GetMapping("/user/exportExcel")
    public ResponseEntity<byte[]> exportExcel() throws Exception {
        String fileName = "user_data.xlsx"; // 导出的文件名

        List<UserBO> userList = userMapper.selectList(null); // 生成要导出的数据，这里假设有一个生成数据的方法

        // 创建Excel工作簿并写入数据
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        EasyExcel.write(outputStream, UserBO.class).sheet("用户信息").doWrite(userList);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
        headers.setContentDispositionFormData("attachment", URLEncoder.encode(fileName, StandardCharsets.UTF_8.name()));
        return new ResponseEntity<>(outputStream.toByteArray(), headers, HttpStatus.OK);
    }
}
